using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;
using Newtonsoft.Json;
using SmartLink.EnumLibrary;
using SmartLink.DTOS;
using SmartLink.Infrastructure.Logger;
using SmartLink.Infrastructure;
using SmartLink.DBLogger;

namespace SmartLink.WebApi.Filter
{
    /// <summary>
    /// 全局API异常记录
    /// </summary>
    public class ApiHandleErrorAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            base.OnException(filterContext);

            //异常信息
            //ErrorMessage msg = new ErrorMessage(filterContext.Exception, "接口");
            //接口调用参数
            var headers = filterContext.Request.Headers;
            IEnumerable<string> values = null;
            //var headerToken = headers.TryGetValues("token", out values);
            //if (!headerToken || values == null || values.Count() == 0)
            //{
            //    filterContext.Response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError,
            //                             new Results { State = StateCodeEnum.Token无效.GetHashCode(), Message = "token无效！" }); ;
            //    return;
            //}
            string pageToken = values.ToList()[0];
            int userId = JWTHelper.GetUserIdFromToken(pageToken);
            //错误记录
            string exMsg = JsonConvert.SerializeObject(filterContext.Exception.Message, Formatting.Indented);
            LogToDBHelper.GetInstance().LogError(filterContext.Exception.Source, exMsg, userId);
            var errorMessage = filterContext.Exception.Message;

            filterContext.Response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, new Results { State = StateCodeEnum.系统异常.GetHashCode(), Message = errorMessage + "\r\n" + filterContext.Exception.StackTrace });
        }
    }
}